<template>
    <div class="default-main ba-table-box">
        <el-alert class="ba-table-alert" v-if="baTable.table.remark" :title="baTable.table.remark" type="info" show-icon />

        <!-- 表格顶部菜单 -->
        <TableHeader
            :buttons="['refresh', 'add', 'edit', 'delete', 'comSearch', 'quickSearch', 'columnDisplay']"
            :quick-search-placeholder="t('quick Search Placeholder', { fields: t('xInsurance.quick Search Fields') })"
        >   
        <el-radio-group v-model="state.currentType" style="margin-left:12px" @change="typeChange">
            <el-radio-button label="1" >按箱号查</el-radio-button>
            <el-radio-button label="2" >按保单查</el-radio-button>
        </el-radio-group>
            <FileUpload v-show="state.currentType == '2'" action="xInsurance/importData" name="箱号导入" />
        </TableHeader>

        <!-- 表格 -->
        <!-- 要使用`el-table`组件原有的属性，直接加在Table标签上即可 -->
        <Table ref="tableRef" :key="state.currentType" row-key="TCNO">
            <template #columnPrepend v-if="state.currentType == '1'">
                <el-table-column  type="expand">
                    <template #default="props">
                        <el-table :data="props.row.claims" :border="false" row-key="ID" @row-dblclick="(row:any)=>handleReportClick(row,'view')">
                            <el-table-column width="100">
                            </el-table-column>
                            <el-table-column label="出险日期" prop="CXDATE" />
                            <el-table-column label="理赔金额" prop="MONEY" />
                            <!-- <el-table-column label="费用类型" prop="ITEMCODE" /> -->
                            <el-table-column label="事故描述" prop="DESCRIBE" />
                            <el-table-column label="备注" prop="DEMO" />
                            <el-table-column label="操作" >
                                <template #default="scope">
                                    <el-button type="primary" class="table-row-edit table-operate" size="small" @click="handleReportClick(scope.row,'edit')">
                                        <i class="fa fa-pencil icon"></i>
                                    </el-button>
                                    <el-popconfirm title="确认删除选中记录?"  @confirm="handleReportDel(scope.row)">
                                        <template #reference>
                                        <el-button type="danger" class="table-row-delete table-operate" :icon="Delete" size="small" />
                                        </template>
                                    </el-popconfirm>
                                </template>
                            </el-table-column>
                        </el-table>
                    </template>
                </el-table-column>
            </template>
        </Table>

        <!-- 表单 -->
        <PopupForm />
        <el-dialog
            :model-value="report.operate?true:false"
            :title="report.operate ? t(report.operate) : ''+'出险' "
            width="800px"
            @close="handleClose"
        >
            <div
                class="ba-operate-form"
                :class="'ba-' + report.operate + '-form'"
                :style="'width: calc(100% - '  + '80px)'"
            >
                <el-form
                    ref="formRef"
                    :model="report.items"
                    label-position="right"
                    :label-width="'100px'"
                    :disabled="report.operate == 'view'"
                    :rules="rules"
                >
                <FormItem :label="t('xClaims.POLICYNO')" type="string" v-model="report.items!.POLICYNO" prop="POLICYNO" :input-attr="{ placeholder: t('Please input field', { field: t('xClaims.POLICYNO') }),disabled:true }" />
                <FormItem 
                    :label="t('xClaims.TCNO')" 
                    v-model="report.items!.TCNO" 
                    prop="TCNO" 
                    type="remoteSelect"
                        :input-attr="{
                            pk: 'tcno',
                            field: 'tcno',
                            'remote-url':'/admin/tz/all?sql='+`select tcno from x_pot where status='SYZ'`,
                            placeholder: t('Click Select'),
                            disabled:true
                        }"

                />
                <FormItem :label="t('xClaims.CXDATE')" type="datetime" v-model="report.items!.CXDATE" prop="CXDATE" :input-attr="{ placeholder: t('Please select field', { field: t('xClaims.CXDATE') }) }" />
                <FormItem :label="t('xClaims.MONEY')" type="number" prop="MONEY" v-model.number="report.items!.MONEY" :input-attr="{ step: '0.01', placeholder: t('Please input field', { field: t('xClaims.MONEY') }) }" />
                <FormItem :label="t('xClaims.DESCRIBE')" type="textarea" v-model="report.items!.DESCRIBE" prop="DESCRIBE" :input-attr="{ rows: 3, placeholder: t('Please input field', { field: t('xClaims.DESCRIBE') }) }"  />
                <FormItem :label="t('xClaims.DEMO')" type="textarea" v-model="report.items!.DEMO" prop="DEMO" :input-attr="{ rows: 3, placeholder: t('Please input field', { field: t('xClaims.DEMO') }) }"  />
                <FormItem
                    :label="'事故图片'"
                    type="image"
                    v-model="report.items!.FILEPATH"
                    prop="FILEPATH"
                    :input-attr="{ placeholder: t('Please input field', { field: '事故图片' }) }"
                />
                <FormItem :label="t('xClaims.OP')" type="string" v-model="report.items!.OP" prop="OP" :input-attr="{ placeholder: '当前操作人' ,disabled:true}" />
                <FormItem :label="t('xClaims.OPTIME')" type="datetime" v-model="report.items!.OPTIME" prop="OPTIME" :input-attr="{ placeholder: '当前时间',disabled:true }" />
                </el-form>
            </div>
            <template #footer>
            <span class="dialog-footer" v-if="report.operate != 'view'">
                <el-button @click="report.operate = ''">取消</el-button>
                <el-button type="primary" @click="handleReportSave(formRef)">
                保存
                </el-button>
            </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, provide, onMounted, reactive, computed } from 'vue'
import baTableClass from '/@/utils/baTable'
import { xInsurance ,xClaims } from '/@/api/controllerUrls'
import { defaultOptButtons } from '/@/components/table'
import { baTableApi } from '/@/api/common'
import { useI18n } from 'vue-i18n'
import PopupForm from './popupForm.vue'
import Table from '/@/components/table/index.vue'
import TableHeader from '/@/components/table/header/index.vue'
import FormItem from '/@/components/formItem/index.vue'
import { ElForm, ElMessage, FormInstance, FormItemRule } from 'element-plus'
import { buildValidatorData } from '/@/utils/validate'
import {
  Delete,
  Edit,
} from '@element-plus/icons-vue'
import FileUpload from '/@/components/fileUpload/index.vue'

const { t } = useI18n()
const tableRef = ref()

const state:{
    currentType:string
} = reactive({
    currentType:'1'
})

const column:any = computed(()=>{
    return [
            // { type: 'selection', align: 'center', operator: false },
            { label: '箱号', prop: 'TCNO', align: 'center' , show:state.currentType == '1' },
            { label: t('xInsurance.POLICYNO'), prop: 'POLICYNO', align: 'center' },
            { label: '罐箱数量', align: 'center',show:state.currentType == '2',render: 'customTemplate', customTemplate: (row: any) => {
                let count = row.pot&&row.pot.length?row.pot.length:'-'
                return '<span>' + count+ '</span>';
            } },
            { label: t('xInsurance.POLICY'), prop: 'POLICY', align: 'center' },
            { label: t('xInsurance.STARTDATE'), prop: 'STARTDATE', align: 'center', render: 'datetime', sortable: 'custom', operator: 'RANGE', width: 160 },
            { label: t('xInsurance.ENDDATE'), prop: 'ENDDATE', align: 'center', render: 'datetime', sortable: 'custom', operator: 'RANGE', width: 160 },
            { label: '保险范围', prop: 'NOTE', align: 'center', sortable: 'custom', operator: 'RANGE', width: 160 },
            { label: t('xInsurance.MONEY'), prop: 'MONEY', align: 'center', operator: 'RANGE' },
            { label: t('xInsurance.SUNINSURED'), prop: 'SUNINSURED', align: 'center', operator: 'RANGE' },
            { label: t('xInsurance.POLICYPATH'), prop: 'POLICYPATH', align: 'center' },
            // { label: t('xInsurance.OP'), prop: 'OP', align: 'center' },
            // { label: t('xInsurance.OPTIME'), prop: 'OPTIME', align: 'center', render: 'datetime', sortable: 'custom', operator: 'RANGE', width: 160 },
            // { label: t('xInsurance.VALID'), prop: 'VALID', align: 'center' },
            { label: t('operate'), align: 'center', width: 150, render: 'buttons', buttons: optButtons, operator: false },
        ]
})

const report = reactive({
    operate:'',
    items:{
        POLICYNO:'',
        TCNO:'',
        CXDATE:'',
        MONEY:'',
        DESCRIBE:'',
        DEMO:'',
        OP:'',
        OPTIME:'',
        FILEPATH:''
    },
})
const rules: Partial<Record<string, FormItemRule[]>> = reactive({
    CXDATE: [buildValidatorData({name: 'required', message: t('Please enter the correct field', { field: t('xClaims.CXDATE') })})],
    MONEY: [buildValidatorData({name: 'required', message: t('Please enter the correct field', { field: t('xClaims.MONEY') })})],
    DESCRIBE: [buildValidatorData({name: 'required', message: t('Please enter the correct field', { field: t('xClaims.DESCRIBE') })})],
    OPTIME: [buildValidatorData({name: 'date', message: t('Please enter the correct field', { field: t('xClaims.OPTIME') })})],
})

// 自定义一个新的按钮
let newButton: any = [
    {
        // 渲染方式:tipButton=带tip的按钮,confirmButton=带确认框的按钮,moveButton=移动按钮
        render: 'tipButton',
        // 按钮名称
        name: 'info',
        // 鼠标放置时的 title 提示
        title: '新增出险',
        // 直接在按钮内显示的文字，title 有值时可为空
        text: '',
        // 按钮类型，请参考 element plus 的按钮类型
        type: 'primary',
        // 按钮 icon
        icon: 'fa fa-plus icon',
        class: 'table-row-info',
        // tipButton 禁用 tip
        disabledTip: false,
        // 自定义点击事件
        click: (row: any, field: any) => {
            report.operate = 'add'
            // console.log(row)
            report.items.POLICYNO = row.POLICYNO
            report.items.TCNO = row.TCNO

        },
        // 按钮是否显示，请返回布尔值
        display: (row: any, field: any) => {
            return state.currentType == '1'
        },
        attr: {}
    },
]

const optButtons = newButton.concat(defaultOptButtons(["edit","delete"]))  


const baTable = new baTableClass(
    new baTableApi(xInsurance),
    {
        pk: 'POLICYNO',
        column: column.value,
        dblClickNotEditColumn: [undefined, ],
        defaultOrder: { prop: 'TCNO', order: 'desc' },
    },
    {
        defaultItems: [],
    }
)

provide('baTable', baTable)

const route = useRoute()
onMounted(() => {
    baTable.table.ref = tableRef.value
    baTable.table.filter!.type = state.currentType //1 按箱号  2 
    if(route.query.code){
        baTable.table.filter!.code = route.query.code
    }
    baTable.mount()
    baTable.getIndex()?.then(() => {
        // baTable.initSort()
        // baTable.dragSort()
    })
})

const typeChange = ()=>{
    baTable.table.filter!.type = state.currentType 
    baTable.getIndex()?.then(()=>{
        baTable.table.column = column.value
        baTable.initSort()
    })
}

const handleReportClick = (item:any,type:string)=>{
    report.operate = type
    report.items = item
}


const formRef = ref<FormInstance>()
const handleReportSave = (formEl:FormInstance|undefined)=>{
    if(!formEl) return
    formEl.validate((valid)=>{
        if(valid){
            createAxios({
                url:xClaims+ report.operate,
                method:'post',
                data:report.items
            }).then((res:any)=>{
                ElMessage({
                    message:'保存成功',
                    type:'success'
                })
                report.operate = ''
                baTable.getIndex()?.then(() => {
                    // baTable.initSort()
                    // baTable.dragSort()
                })
            })
        }
    })
}


const handleReportDel = (item:any)=>{

    createAxios({
        url:xClaims+'del',
        method:'DELETE',
        data:{
            ids:[item.ID]
        }
    }).then((res:any)=>{
        ElMessage({
            message:'删除成功',
            type:'success'
        })
        baTable.getIndex()
        report.operate = ''
    })
}

const handleClose = ()=>{
    report.operate = ''
    report.items = {
        POLICYNO:'',
        TCNO:'',
        CXDATE:'',
        MONEY:'',
        DESCRIBE:'',
        DEMO:'',
        OP:'',
        OPTIME:''
    }
    return true
}
</script>

<script lang="ts">
import { defineComponent } from 'vue'
import createAxios from '/@/utils/axios'
import { useRoute } from 'vue-router'
import validate from '/@/lang/pages/en/validate'
export default defineComponent({
    name: 'xInsurance',
})
</script>

<style scoped lang="scss"></style>
